/*
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.speedydial;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.speedydial.model.SettingsModel;

/**
 * Speedy-Dial contacts database access helper class. Defines the basic CRUD operations
 * 
 */
public class EventBusDBAdapter {

    public static final String KEY_DESTINATARY_ID = "destinatary_id";
    public static final String KEY_MESSAGE_ID = "message_id";
    public static final String KEY_EVENT_TYPE = "event_type";
    public static final String KEY_ROWID = "_id";

    private static final String TAG = "EventBusDbAdapter";
    private static final String TABLE_NAME = "eventBus";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    public static enum OrientationSettingsKey {
		ORIENTATION_X,
		ORIENTATION_Y,
		ORIENTATION_Z
	}
    
    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
            "create table " + TABLE_NAME +" (" + KEY_ROWID  
                    +  " integer primary key autoincrement, "
                    + KEY_DESTINATARY_ID + " text not null, " 
                    + KEY_MESSAGE_ID + " text not null, " 
                    + KEY_EVENT_TYPE + " text not null);";

    private static final String DATABASE_NAME = "data";
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public EventBusDBAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the sms contact database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public EventBusDBAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
    
    public void close() {
        mDbHelper.close();
    }


    /**
     * Creates or replaces the existing parameterr
     * 
     * @param setting object with the parameters
     * @return rowId or -1 if failed
     */
    public long createSetting(SettingsModel setting) {
    	
    	if( setting == null ){
    		return -1l;
    	}
    	
    	// first select if the key name exists
    	Cursor c = getValueByKeyName(setting.name);
    	
    	if ( c != null && c.getCount() > 0){
    		updateSetting(setting);
    		return 10l;
    	}
    	// then save
    	
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_DESTINATARY_ID, setting.name);
        initialValues.put(KEY_MESSAGE_ID, setting.value );
        initialValues.put(KEY_EVENT_TYPE, setting.description );

        return mDb.insert(TABLE_NAME, null, initialValues);
    }

    /**
     * Delete the note with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteNote(long rowId) {

        return mDb.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all notes in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllContacts() {

        return mDb.query(TABLE_NAME, // table
        		getColumns(), //cols
                null, // selection args
                null, // group by
                null, // having
                KEY_DESTINATARY_ID,  // order by 
                null);  // limit
    }
    
    private String[] getColumns(){
    	return new String[] {KEY_ROWID, KEY_DESTINATARY_ID,KEY_MESSAGE_ID, KEY_EVENT_TYPE};
    }

    /**
     * Obtiene la super clase para permitir moverse entre los diferentes 
     * registros
     * 
     * @param sortBy
     * @return
     */
    
    
    public Cursor getValueByKeyName(String keyName){
    	Cursor mCursor =
            mDb.query(
            		TABLE_NAME, 
            		null, 
                    KEY_DESTINATARY_ID + "=?", 
                    new String[]{keyName},
                    null, 
                    null, 
                    null, 
                    null);
    
		if (mCursor != null) {
			mCursor.moveToFirst();
		}

		return mCursor;
    }
    
    /**
     * Return a Cursor positioned at the note that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchContact(long rowId) throws SQLException {

        Cursor mCursor =
                mDb.query(true, 
                		TABLE_NAME, 
                		getColumns(), 
                        KEY_ROWID + "=" + rowId, 
                        null,
                        null, 
                        null, 
                        KEY_DESTINATARY_ID, 
                        null);
        
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        
        return mCursor;

    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param SMSContact
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateSetting(SettingsModel contact) {
        ContentValues args = new ContentValues();
        args.put(KEY_DESTINATARY_ID, contact.name );
        args.put(KEY_MESSAGE_ID, contact.value );
        args.put(KEY_EVENT_TYPE, contact.description );

        return mDb.update(TABLE_NAME, 
        		          args, 
        		          KEY_ROWID + "=" + contact.ID, 
        		          null) > 0;
    }
    
    
    }
